//
//  ClubGamesGiftListViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/19.
//

import UIKit
import WebKit

class ClubGamesGiftListViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(16.font_semiBold).end()
    private let recordButton = c_make_ex(UIButton.self)
        .color("#2E3033").border("#C8C9CC", width: 1)
        .corner(13).text("记录").font(12.font_semiBold).end()
    private lazy var progressView: UIProgressView = {
        let view = UIProgressView(progressViewStyle: .bar)
        view.progress = 0
        view.trackTintColor = "#F4F4F5".toColor
        view.progressTintColor = "#52A260".toColor
        return view
    }()
    
    private lazy var webView: WKWebView = {
        let contentController = WKUserContentController()
        contentController.add(self, name: "jsPopHandler")
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = contentController
        let view = WKWebView(frame: .zero, configuration: configuration)
        view.navigationDelegate = self
        view.uiDelegate = self
        // 禁止缩放手势
        let source: String = "var meta = document.createElement('meta');" +
        "meta.name = 'viewport';" +
        "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
        "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);";
        let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        view.configuration.userContentController.addUserScript(script)
        
        view.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        view.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        view.scrollView.backgroundColor = .clear
        return view
    }()
    
    var recordUrl: String = ""
    var urlString: String? {
        didSet {
            var webUrl: URL?
            if let url = URL(string: urlString ?? "") {
                webUrl = url
            }
            guard let webUrl else { return }
            
            WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { recods in
                recods.forEach{
                    WKWebsiteDataStore.default().removeData(ofTypes: $0.dataTypes, for: [$0]) { }
                }
            }
            webView.load(URLRequest(url: webUrl))
        }
    }
    
    var recordUrlString: String? {
        didSet {
            var webUrl: URL?
            if let url = URL(string: recordUrlString ?? "") {
                webUrl = url
            }
            guard let webUrl else { return }
            
            WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { recods in
                recods.forEach{
                    WKWebsiteDataStore.default().removeData(ofTypes: $0.dataTypes, for: [$0]) { }
                }
            }
            webView.load(URLRequest(url: webUrl))
        }
    }
    
    var JSData: [String: String]? {
        didSet{
            guard let dict = JSData else { return }
            
            if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []),
               let jsonString = String(data: jsonData, encoding: .utf8) {
                
                webView.evaluateJavaScript("receiveDataFromSwift(\(jsonString))") { (result, error) in
                    if let error = error {
                        print("JavaScript error: \(error.localizedDescription)")
                    } else {
                        print("Data passed to JavaScript successfully")
                    }
                }
            }
        }
    }
    
    var gameID: String = ""
    var type: Int = 0 {
        didSet{
            if type == 0 {
                recordButton.isHidden = false
                titleLabel.text = "礼包列表"
            }else if type == 1{
                recordButton.isHidden = false
                titleLabel.text = "领取优惠券"
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            recordButton
            webView
            progressView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.CenterY == backButton.CenterY
        titleLabel.Leading == backButton.Trailing
        recordButton.trailing(12).width(56).height(26)
        recordButton.CenterY == backButton.CenterY
        progressView.leading(0).trailing(0).height(2.0).top(.navi_height)
        webView.fillContainer().top(.navi_height)
        
        backButton.addTarget(self, action: #selector(clickWebBackButton), for: .touchUpInside)
        recordButton.addTarget(self, action: #selector(clickRecordButton), for: .touchUpInside)
    }
    
    @objc private func clickWebBackButton() {
        
        if recordUrlString?.count ?? 0 <= 0 {
            self.navigationController?.popViewController(animated: true)
        }else{
            recordUrlString = ""
            recordButton.isHidden = false
            urlString = recordUrl
        }
    }
    
    @objc private func clickRecordButton(){
        
        var user_id = ""
        if let uid = UserDefaultsManager.getString(forKey: .uid) {
            user_id = uid
        }
        let tStr = RaeRequestParameterConfig.shared.getTStr()
        let sign = RaeRequestParameterConfig.shared.encrySign()
        
        if type == 0 {
            let url = RaeRequestParameterConfig.shared.baseUrlStr + "ct=app2021&ios=1&ac=lb_log&uid=" + user_id + "&t=" + tStr + "&sign=" + sign + "&gid=" + self.gameID
            self.recordUrlString = url
        }else{
            let url = RaeRequestParameterConfig.shared.baseUrlStr + "ct=app2021&ios=1&ac=coupon_log&uid=" + user_id + "&t=" + tStr + "&sign=" + sign + "&gid=" + self.gameID
            self.recordUrlString = url
        }
        recordButton.isHidden = true
//        titleLabel.text = "领取记录"
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") {
            progressView.isHidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        }else if (keyPath == "title") {
            if self.titleLabel.text?.count == 0 {
                title(webView.title)
            }
        }
    }
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        progressView.removeFromSuperview()
    }
}

//MARK: - WKNavigationDelegate
extension ClubGamesGiftListViewController: WKNavigationDelegate {
    
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.titleLabel.text = self.webView.title
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
    }
    
    // 接收到服务器跳转请求之后调用
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    
    // 在收到响应后，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    // 在发送请求之前，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        progressView.progress = 0
        decisionHandler(.allow, preferences)
    }
}

//MARK: - WKUIDelegate, WKScriptMessageHandler
extension ClubGamesGiftListViewController: WKUIDelegate, WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if message.name == "jsPopHandler" {
            if let body = message.body as? String {
//                print("JavaScript message: \(body)")
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alertController = UIAlertController(title: "Tips", message: message, preferredStyle: .alert)
        let actionOk = UIAlertAction(title: "OK", style: .default) { alert in
            completionHandler()
        }
        alertController.addAction(actionOk)
        present(alertController, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alertController = UIAlertController(title: "Tips", message: message, preferredStyle: .alert)
        let actionOk = UIAlertAction(title: "OK", style: .default) { alert in
            completionHandler(true)
        }
        let actionCancel = UIAlertAction(title: "Cancel", style: .default) { alert in
            completionHandler(false)
        }
        alertController.addAction(actionOk)
        alertController.addAction(actionCancel)
        present(alertController, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        completionHandler("")
    }
    
}
